package com.lbagroup.giscovery;

//import android.app.Activity;
import java.io.BufferedInputStream;
import java.io.File;
import java.net.URL;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.MarshalBase64;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;

import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.os.Message;
import android.provider.MediaStore;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import com.lbagroup.giscovery.R;

/** 
 * Activity for Sharing data from the user
 * 
 * This activity is used to when user clicks to share data from the MainActivity. User can type text, use 
 * the barcode scanner and take pictures. All these results can then be uploaded to MovingObject.org and be visible
 * at the Giscovery Facebook application. 
 * 
 * @author XH 
 * @version 2011.1105 
 * @since 0.1 
 */  
public class ShareContent extends Activity {

        
    private static final int ABOUT_ID = Menu.FIRST; // defines the id for the about option menu 
    private static final int FBLOGIN_ID=Menu.FIRST+1; // defines the id fr the facebook login option menu
    private int groupID=1;  // ID of the option menu group
    private static final String PACKAGE_NAME = "com.lbagroup.giscovery";
    
   /**
    * The following defines the preference file to save the facebook user login information
    */
    public static final String MO_PROF="ProferenceFile";
    public static final String FB_USERID = "FBUserid";
    public static String FBUserid = " ";
    public static final String FB_USERFULLNAME = "FBUserfullname";
    public static String FBUserfullname = " ";
    public static final String FB_USERNAME = "FBUsername";
    public static String FBUsername = " ";
    public static final String FB_PASSWORD = "FBPassword";
    public static String FBPassword = " ";
    public static int FB_CHECKED=0; // the flag if the user has agree to only share the data with friends or agree to share it in public
    
    /**
     * The following lines keep the variables which holds the values to be sent to the MovingObject.org server through the web service
     */
    private static String mComment=" ";
    private static String mLat=" ";
    private static String mLng=" ";
    private static String mAddress=" ";
    private static String mStrCtnt=" ";
    private static String mStrPicture=" ";
    private Uri imageUri;
    
    public static String result=" "; //this is kept global just for the purpose of debugging
    
    @Override
    public void onCreate(Bundle icicle) {
        
      super.onCreate(icicle);
      setContentView(R.layout.share_screen);
      
      TextView latText = (TextView) findViewById(R.id.SlatText);
      TextView lngText = (TextView) findViewById(R.id.SlngText);
      TextView cntText = (TextView) findViewById(R.id.scanresults);
      TextView addText=(TextView) findViewById(R.id.addressText);
      
      findViewById(R.id.take_a_picture).setOnClickListener(mTakeaPicture);
      findViewById(R.id.scan_barcode).setOnClickListener(mScanBarcode);
      findViewById(R.id.record_voice).setOnClickListener(mRecordVoice);
      findViewById(R.id.take_a_video).setOnClickListener(mTakeaVideo);
      Bundle mBndl=getIntent().getExtras();
      mLat=mBndl.getString("lat_str");
      mLng=mBndl.getString("lng_str");
      mAddress=mBndl.getString("address_str");
      latText.setText(mLat);
      lngText.setText(mLng);
      String strImgPath=mStrPicture; 
      cntText.setText(mStrCtnt);
      addText.setText(mAddress);
    
      ImageView picImgView=(ImageView) findViewById(R.id.SimgView);
      File imageFile = new File(strImgPath);
     if (imageFile.exists()){ // show the image if it exists
         Bitmap bitmapOrg=BitmapFactory.decodeFile(strImgPath);
         int width = bitmapOrg.getWidth();
         int height = bitmapOrg.getHeight();
         int newWidth = 200;
         int newHeight = 200;
         float scaleWidth = ((float) newWidth) / width;
         float scaleHeight = ((float) newHeight) / height;
         Matrix matrix = new Matrix();
         matrix.postScale(scaleWidth, scaleHeight);
         matrix.postRotate(45);
         Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);
         BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
         picImgView.setImageDrawable(bmd);
         picImgView.setScaleType(ScaleType.CENTER);

      } 
      findViewById(R.id.btn_ok).setOnClickListener(mBTNOK);
      findViewById(R.id.btn_cancel).setOnClickListener(mBTNCANCEL);
      
      CheckBox mchkfb=(CheckBox)findViewById(R.id.chkFB);
      mchkfb.setOnCheckedChangeListener(mCHKFB);

      }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
      super.onCreateOptionsMenu(menu);
      menu.add(groupID, ABOUT_ID, 0, R.string.about_menu)
          .setIcon(android.R.drawable.ic_menu_info_details);
      menu.add(groupID,FBLOGIN_ID ,0,"Facebook Account");  
      return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
     switch (item.getItemId()) {
        case ABOUT_ID:
          int versionCode = 0;
          String versionName = "alpha release";
          try {
            PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
            versionCode = info.versionCode;
            versionName = info.versionName;
          } catch (PackageManager.NameNotFoundException e) {
          }
          AlertDialog.Builder builder = new AlertDialog.Builder(this);
          builder.setTitle(getString(R.string.app_name) + " " + versionName + " (" + versionCode +
              ")");
          builder.setMessage(getString(R.string.about_message));
          builder.setPositiveButton(R.string.ok_button, null);
          builder.show();
          break;
        case FBLOGIN_ID:
			Intent intent1 = new Intent(); 
            intent1.setClassName(ShareContent.this, FBLogin.class.getName());
            startActivity(intent1); 
        	break;
      }
     
      return super.onOptionsItemSelected(item);
    }
    
    /**
     * Method that is triggered when user check or uncheck the option of sharing the data to public or only to friends
     * 
     */
    public final CheckBox.OnCheckedChangeListener mCHKFB = new CheckBox.OnCheckedChangeListener() {
      @Override
		public void onCheckedChanged(CompoundButton buttonView,
				boolean isChecked) {
			if(isChecked){
				SharedPreferences pref = getSharedPreferences(MO_PROF,MODE_PRIVATE);   
				String FBusername = pref.getString(FB_USERNAME, null);
				String FBuserid = pref.getString(FB_USERID, null);
				FB_CHECKED=1;	
			          AlertDialog.Builder builder = new AlertDialog.Builder(ShareContent.this);
			          builder.setMessage("Your name will not be mentioned in shared message. Continue with this option?")
			                 .setCancelable(false)
			                 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
			                     public void onClick(DialogInterface dialog, int id) {
			                    	 FB_CHECKED=0;
			                    	 dialog.cancel();
			                     }
			                 })
			                 .setNegativeButton("No", new DialogInterface.OnClickListener() {
			                     public void onClick(DialogInterface dialog, int id) {
			                    	 CheckBox mchkfb=(CheckBox)findViewById(R.id.chkFB);
			                    	 mchkfb.setChecked(false);
			                    	 FB_CHECKED=2;
			                          dialog.cancel();
			                     }
			                 });
			          AlertDialog alert = builder.create();
			          alert.show();
				}
		}    
    };
    
    /**
     * Method that is triggered when user chooses to click the take picture button.
     * Here the external camera application is called to complete the picture-taking action. 
     */
    public final Button.OnClickListener mTakeaPicture = new Button.OnClickListener() {
        public void onClick(View v) {
           
          //define the file-name to save photo taken by Camera activity
            String fileName = "lbademo.jpg";
            //create parameters for Intent with filename
            ContentValues values = new ContentValues();
            values.put(MediaStore.Images.Media.TITLE, fileName);
            values.put(MediaStore.Images.Media.DESCRIPTION,"Image capture by camera");
            //imageUri is the current activity attribute, define and save it for later usage (also in onSaveInstanceState)
            imageUri = getContentResolver().insert(
                  MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
            //create new Intent
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
            intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
            startActivityForResult(intent, 1);

            }
      };
      
      
      /**
       * Method that is triggered when user clicks to take a video. 
       * this method is not implemented yet. 
       * 
       */
      public final Button.OnClickListener mTakeaVideo=new Button.OnClickListener() {
          public void onClick(View v){

              //AlertDialog.Builder builder = new AlertDialog.Builder().create(); .Builder(this);
              AlertDialog alertDialog = new AlertDialog.Builder(ShareContent.this).create();
              alertDialog.setTitle("Information");
              alertDialog.setMessage("This feature is not included in this demo version.");
              alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                 public void onClick(DialogInterface dialog, int which) {
                    // here you can add functions
                 }
              });
              alertDialog.setIcon(R.drawable.info_icon);
              alertDialog.show();
       
      }};
         
      /**
       * Method that is triggered when user chooses to click the recordvoice button.
       * This method is not implemented yet
       * 
       */
      public final Button.OnClickListener mRecordVoice=new Button.OnClickListener() {
              public void onClick(View v){
                  AlertDialog alertDialog = new AlertDialog.Builder(ShareContent.this).create();
                  alertDialog.setTitle("Information");
                  alertDialog.setMessage("This feature is not included in this demo version.");
                  alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int which) {
                        // here you can add functions
                     }
                  });
                  alertDialog.setIcon(R.drawable.info_icon);
                  alertDialog.show(); 
       
      }};
              
      /**
       * Method that is triggered when user clicks to scan a barcode. 
       * In this method, the external ZXing Barcode Scanner application is called to complete the task
       * 
       */
      public final Button.OnClickListener mScanBarcode = new Button.OnClickListener() {
        public void onClick(View v) {
            
            boolean installed  = appInstalledOrNot("com.google.zxing.client.android");
            if(installed){
              Intent intent = new Intent("com.google.zxing.client.android.SCAN");
              startActivityForResult(intent, 1235);
            }
            else{
                
                AlertDialog.Builder builder = new AlertDialog.Builder(ShareContent.this);
                builder.setMessage("This feature requires the Barcode Scanner Application from ZXing. Download this App from Android Market?")
                       .setCancelable(false)
                       .setIcon(R.drawable.info_icon)
                       .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                                 Intent goToMarket = null;
                                 goToMarket = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=com.google.zxing.client.android"));
                                 startActivity(goToMarket);
                           }
                       })
                       .setNegativeButton("No", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int id) {
                                dialog.cancel();
                           }
                       });
                AlertDialog alert = builder.create();
                alert.show();
                  
            }

        }
      };
      
      /**
       * Method that check if an application is installed or not
       * 
       * @param uri Name of the application
       * @return a boolean value if exists (true)or not (false) 
       */
      private boolean appInstalledOrNot(String uri){
          PackageManager pm = getPackageManager();
          boolean app_installed = false;
          try{
              pm.getPackageInfo(uri, PackageManager.GET_ACTIVITIES);
              app_installed = true;
          }
          catch (PackageManager.NameNotFoundException e){
                         app_installed = false;
          }
                  return app_installed ;
      }
      
    /**
     * Method that is triggered when the OK button clicked. 
     * After the OK button is clicked, user's input is saved and sent to MovingObject.org through the web services via a separate thread. 
     */
    public final Button.OnClickListener mBTNOK = new Button.OnClickListener() {
      public void onClick(View v) {
      
          
			SharedPreferences pref = getSharedPreferences(MO_PROF,MODE_PRIVATE);   
			String FBuserid = pref.getString(FB_USERID, null);
			String FBuserfullname = pref.getString(FB_USERFULLNAME, null);
			String FBusername = pref.getString(FB_USERNAME, null);

			if (FBusername == null || FBuserid == null) {
					Intent intent = new Intent(); 
		            intent.setClassName(ShareContent.this, FBLogin.class.getName());
		            startActivity(intent); 
		    }
		   
		        	CheckBox mchkfb=(CheckBox)findViewById(R.id.chkFB);
		        	if(mchkfb.isChecked()){
						 FB_CHECKED=0;
			        }
		        	else{
		        		FB_CHECKED=2;
		        	}

		          FBUserid=FBuserid;
		          FBUsername=FBusername;
		          FBUserfullname=FBuserfullname;
		          TextView txtVW_Comment = (TextView) findViewById(R.id.usercomments);
		          mComment=txtVW_Comment.getText().toString();
		           
		          UploadDataAsyncTask task = new UploadDataAsyncTask();
		          task.applicationContext = ShareContent.this;
		          task.execute();
			
      }
    };

    /**
     * This method receives all the results after calling different internal or external activities. 
     * All calls to barcode scanners, cameras are handled here. 
     */
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode == 1235) {
          if (resultCode == RESULT_OK) {
        	   // if the barcode scanner returns a successful result, keeps the result to mStrCtnt
                String contents = intent.getStringExtra("SCAN_RESULT");
               mStrCtnt=contents;
               if(mStrCtnt.trim().length()>0)
               {
	               ViewGroup mvg=(ViewGroup)findViewById(R.id.llbarcode);
	               mvg.setVisibility(View.VISIBLE);
	               TextView txtContent = (TextView) findViewById(R.id.scanresults);
	               txtContent.setText(mStrCtnt);
               }
               
          } else if (resultCode == RESULT_CANCELED) {
          }
        }
        else if (requestCode == 1){
                if (resultCode == RESULT_OK) {
                	// if the camera return successfully with a result picture, shrink the 
                	// returned picture to the expected size, save the picture and show the picture in 
                	// the current activity. 
                    File mF=convertImageUriToFile(imageUri,this);
                    mStrPicture=mF.getPath();
                    
                    Bitmap mBM= ShrinkBitmap(mStrPicture,300,200);
                    mStrPicture=SavePicture(mBM);
                    
                    File imageFile = new File(mStrPicture);
                    
                    
                    if (imageFile.exists()){
                       
                        Bitmap bitmapOrg=BitmapFactory.decodeFile(mStrPicture);
                        int width = bitmapOrg.getWidth();
                        int height = bitmapOrg.getHeight();
                        int newWidth = 200;
                        int newHeight = 200;
                        float scaleWidth = ((float) newWidth) / width;
                        float scaleHeight = ((float) newHeight) / height;
                        Matrix matrix = new Matrix();
                        matrix.postScale(scaleWidth, scaleHeight);
                        matrix.postRotate(45);
                        Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);
                        BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
                        ImageView picImgView=(ImageView) findViewById(R.id.SimgView);
                        picImgView.setImageDrawable(bmd);
                        picImgView.setScaleType(ScaleType.CENTER);

                     } 
                } else if (resultCode == RESULT_CANCELED) {
                }
         }
      }        
    
    /**
     * This method saves the bitmap data to a picture and return the directory of the picture. 
     * @param bm the bitmap dataset
     * @return directory of the saved image file
     */
    public String SavePicture(Bitmap bm){
        FileOutputStream outStream;
        String strOutput=" ";
        int quality=50;
        try {
            File sdImageMainDirectory = new File("/sdcard/giscovery");
            if(!sdImageMainDirectory.exists()){
                sdImageMainDirectory.mkdirs();
            }
            String mstrPicture=sdImageMainDirectory.toString()+String.format("/%d.jpg", System.currentTimeMillis());
            strOutput=mstrPicture;
            outStream = new FileOutputStream(mstrPicture);
            BufferedOutputStream bos = new BufferedOutputStream(outStream);
            bm.compress(CompressFormat.JPEG, quality, bos);
            bos.flush();
            bos.close();
            
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
        }
        return strOutput;
    }
    
    /**
     * This method shrinks a bitmap image file to an expected width and height size
     * @param file directory of the image file
     * @param width expected width
     * @param height expected height
     * @return result bitmap dataset
     */
    public Bitmap ShrinkBitmap(String file, int width, int height){
           
        BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
           bmpFactoryOptions.inJustDecodeBounds = true;
           Bitmap bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
            
           int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)height);
           int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)width);
            
           if (heightRatio > 1 || widthRatio > 1)
           {
            if (heightRatio > widthRatio)
            {
             bmpFactoryOptions.inSampleSize = heightRatio;
            } else {
             bmpFactoryOptions.inSampleSize = widthRatio;
            }
           }
            
           bmpFactoryOptions.inJustDecodeBounds = false;
           bitmap = BitmapFactory.decodeFile(file, bmpFactoryOptions);
           
        return bitmap;
       }
    
    /**
     * this method convers an image file to a file
     * @param imageUri location of the image
     * @param activity the current activity context 
     * @return
     */
    public  File convertImageUriToFile (Uri imageUri, Activity activity)  {
        Cursor cursor = null;
        try {
            String [] proj={MediaStore.Images.Media.DATA, MediaStore.Images.Media._ID, MediaStore.Images.ImageColumns.ORIENTATION};
            cursor = activity.managedQuery( imageUri,
                    proj, // Which columns to return
                    null,       // WHERE clause; which rows to return (all rows)
                    null,       // WHERE clause selection arguments (none)
                    null); // Order-by clause (ascending by name)
            int file_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            int orientation_ColumnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.ImageColumns.ORIENTATION);
            if (cursor.moveToFirst()) {
                String orientation =  cursor.getString(orientation_ColumnIndex);
                return new File(cursor.getString(file_ColumnIndex));
            }
            return null;
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
        }

    /**
     * This method is triggered when the cancel button is clicked. 
     */
    public final Button.OnClickListener mBTNCANCEL=new Button.OnClickListener() {
    public void onClick(View v){
            finish();
    }};
    
    /**
     * This method is called when the uploaddata thread is executed.Here the ksoap library is 
     * used to call a webservice at MovingObject.org 
     * 
     * @return result status of the upload
     */
    public static int UploadData(){
        int res=0;
        Bitmap bm;
        String mImgData;
        String mImgFlag="Y";
        MarshalBase64 marshal = new MarshalBase64();
        
        /**
         * The following lines checks if the picture exists. 
         * If so, the image file is taken out ans saved as ByteArray 
         * Then the bytearray is encoded to string and sent to the web sevice as the encoded string.
         */
        if(mStrPicture.trim().length()<5){ 
        	mImgFlag="N";
        	mImgData=" ";
        }
        else{
          bm = BitmapFactory.decodeFile(mStrPicture);
          ByteArrayOutputStream out = new ByteArrayOutputStream();
          bm.compress(CompressFormat.PNG, 100, out);
          byte[] raw = out.toByteArray();
          mImgData=Base64.encodeToString(raw, 1);
        }
          
        /**
         * The following lines starts the calling of the web service.
         * A few namespace and address are defined first.
         * Then the parameters are defined. 
         * After that, the web service is called.  
         */
          String NAMESPACE = "http://tempuri.org/"; // standard value
          String METHOD_NAME = "report6"; // the web service function that receives the uploads of data 
          String SOAP_ACTION = "http://tempuri.org/report6"; // standard value plus the function name
          String URL="http://www.movingobject.org/testfolder/lbademo/phpservice/userupload6.php";
          // this is the full URL of the web service.
          
          
          SoapObject Request = new SoapObject(NAMESPACE, METHOD_NAME);
          
          /**
           * the following lines add all the parameters of the web service call
           */
          PropertyInfo p6 = new PropertyInfo();
          p6.setName("fbuserid");
          p6.setValue(FBUserid);
          p6.setType(String.class);
          Request.addProperty(p6);
          
          PropertyInfo p8 = new PropertyInfo();
          p8.setName("fbusername");
          p8.setValue(FBUsername);
          p8.setType(String.class);
          Request.addProperty(p8);
          
          PropertyInfo p9 = new PropertyInfo();
          p9.setName("fbuserfullname");
          p9.setValue(FBUserfullname);
          p9.setType(String.class);
          Request.addProperty(p9);
          
          PropertyInfo p10 = new PropertyInfo();
          p10.setName("fbflag");
          p10.setValue(FB_CHECKED);
          p10.setType(String.class);
          Request.addProperty(p10);
          
         
          PropertyInfo p1 = new PropertyInfo();
          p1.setName("lat");
          p1.setValue(mLat);
          p1.setType(String.class);
          Request.addProperty(p1);
          
          PropertyInfo p2 = new PropertyInfo();
          p2.setName("lng");
          p2.setValue(mLng);
          p2.setType(String.class);
          Request.addProperty(p2);
          
          PropertyInfo p21 = new PropertyInfo();
          p21.setName("address");
          p21.setValue(mAddress);
          p21.setType(String.class);
          Request.addProperty(p21);

          PropertyInfo p3 = new PropertyInfo();
          p3.setName("productdesc");
          p3.setValue(mStrCtnt);
          p3.setType(String.class);
          Request.addProperty(p3);
          
         
          PropertyInfo p4 = new PropertyInfo();
          p4.setName("comment");
          p4.setValue(mComment);
          p4.setType(String.class);
          Request.addProperty(p4);
          
          PropertyInfo p41 = new PropertyInfo();
          p41.setName("imageflag");
          p41.setValue(mImgFlag);
          p41.setType(String.class);
          Request.addProperty(p41);
     //    Request.addAttribute("imagedata", raw);
          
        PropertyInfo p5 = new PropertyInfo();
          p5.setName("imagedata");
          p5.setValue(mImgData);
          p5.setType(String.class);
          Request.addProperty(p5);
          
        
          SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
          new MarshalBase64().register(envelope);
          envelope.encodingStyle=SoapEnvelope.ENC;
          envelope.setOutputSoapObject(Request);
          envelope.bodyOut=Request;
          
  
          marshal.register(envelope);
          HttpTransportSE androidHttpTransport  = new HttpTransportSE(URL);
          SoapObject response;
          
          
          try
          {
              androidHttpTransport.call(SOAP_ACTION, envelope);
              
             //SoapObject response = (SoapObject)envelope.getResponse();
             // Object response = envelope.getResponse();
              response=(SoapObject)envelope.bodyIn;
              result=response.getProperty(0).toString();
              res =1;

          }
          catch(Exception e)
          {
              e.printStackTrace();
              res=0;
              
          }
          return res;
    }
    
    /** 
     * Inner class for executing the upload data task
     * 
     * This class is used to execute the upload data task in a separate thread 
     * 
     * @author XH 
     * @version 2011.1105 
     * @since 0.1 
     */  
    public class UploadDataAsyncTask extends
    AsyncTask<Void, Integer, Void> {
  
        private ProgressDialog dialog;  // The dialog that returns the upload prograss
        protected Context applicationContext; // context to the current activity
        int iExeResult=0; // upload result status

  @Override
  protected void onPostExecute(Void result) {
   
      this.dialog.cancel();
      if(iExeResult==1){
          AlertDialog.Builder builder = new AlertDialog.Builder(ShareContent.this);
          builder.setMessage("Message uploaded. Back to Map? ")
                 .setCancelable(false)
                 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int id) {
                          ShareContent.this.finish();
                     }
                 })
                 .setNegativeButton("No", new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int id) {
                          dialog.cancel();
                     }
                 });
          AlertDialog alert = builder.create();
          alert.show();
      }
      else
      {
          AlertDialog.Builder builder1 = new AlertDialog.Builder(ShareContent.this);
          builder1.setMessage("Upload error, back to map?")
                 .setCancelable(false)
                 .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int id) {
                          ShareContent.this.finish();
                     }
                 })
                 .setNegativeButton("No", new DialogInterface.OnClickListener() {
                     public void onClick(DialogInterface dialog, int id) {
                          dialog.cancel();
                     }
                 });
          AlertDialog alert = builder1.create();
          alert.show();
      
      }
  }

  @Override
  protected void onPreExecute() {
      this.dialog = ProgressDialog.show(applicationContext, "Upload", "in progress ....", true);
  }

  @Override
  protected Void doInBackground(Void... params) {
      iExeResult=ShareContent.UploadData();
   return null;
  }

  @Override
  protected void onProgressUpdate(Integer... values) {
  }

 }

}
